<template>
  <el-main>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>{{ breadcrumbNameP }}</el-breadcrumb-item>
      <el-breadcrumb-item>{{ breadcrumbName }}</el-breadcrumb-item>
    </el-breadcrumb>
    <el-form :inline="true" :model="formInline" class="el-form query-form el-form--label-right el-form--inline">
      <el-form-item label="标题">
        <el-input size="small" v-model="formInline.transport_sn" placeholder="请输入"></el-input>
      </el-form-item>

      <!-- <el-form-item label="日期">
        <el-date-picker v-model="formInlineD.dataValue" type="daterange" align="right" unlink-panels range-separator="-"
          format="yyyy - MM - dd " value-format="yyyy-MM-dd" start-placeholder="开始时间" end-placeholder="结束时间"
          @change="changeDatePicker">
        </el-date-picker>
      </el-form-item> -->
      <el-form-item>
        <el-button size="small" type="primary" @click="onSearch" icon="el-icon-search">查 询</el-button>
        <el-button size="small" type="primary" @click="handleShow" icon="el-icon-plus">添 加</el-button>
        <!-- <el-button size="small" type="primary" @click="uploadDialogVisible = true"
          icon="el-icon-upload2">导入运单</el-button> -->
        <!-- 
        <el-button size="small" type="primary" icon="el-icon-download">
          <a style="color: #fff;text-decoration: none;" @click="exportReport($event)" href=""
            download="运单导入模板.xlsx">下载模板</a>
        </el-button> -->
        <!-- <el-button size="small" type="primary" @click="onCheck" v-show="is_check" icon="el-icon-upload">批量发布</el-button> -->
      </el-form-item>
    </el-form>
    <el-table :data="tableData" style="margin-top:30px" @selection-change="handleSelectionChange"
      reserve-selection="false" ref="multipleTable">
      <!-- <el-table-column type="selection" width="50" fixed="left" :selectable="selectable"></el-table-column> -->
      <el-table-column prop="sortID" label="排序号"></el-table-column>
      <el-table-column prop="title" label="标题"></el-table-column>
      <el-table-column prop="type" label="分类"></el-table-column>
      <el-table-column prop="content" label="详细内容"></el-table-column>
      <el-table-column prop="creatTime" label="创建时间"></el-table-column>
      <el-table-column prop="coverImg" width="180" label="封面图"></el-table-column>

      <el-table-column label="操作" :width="300" fixed="right">
        <template slot-scope="scope">
          <!-- <el-button size="mini" type="primary" @click="handleShow(scope.$index, scope.row)">添加</el-button> -->
          <el-button size="mini" type="primary" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="primary" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          <el-button size="mini" type="default" @click="handleDetail(scope.$index, scope.row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>


    <el-pagination @current-change="handleCurrentChange" :current-page="formInline.page" :page-size="formInline.limit"
      :hide-on-single-page="true" layout="total, prev, pager, next" :total="total">
    </el-pagination>
    <el-dialog :title="dialogTitle" :visible.sync="addDialogVisible" width="40%" center :before-close="beforeClose"
      custom-class="center_dislog">
      <el-form ref="addForm" :model="addForm" label-width="130px" :rules="addRules">
        <div class="title_import_title"></div>
        <el-form-item label="标题" prop="title">
          <el-input v-model="addForm.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="排序号" prop="sortID">
          <el-input v-model="addForm.sortID"></el-input>
        </el-form-item>
        <el-form-item label="分类" prop="type">
          <el-select v-model="addForm.type" placeholder="请选择" filterable>
            <el-option v-for="(item, index) in truckType" :key="index" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="详细内容" prop="content">
          <el-input v-model="addForm.content" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="文章封面" prop="cover_img">
          <el-upload class="upload-demo" action='/api/upload' :headers="headers" :multiple="true" :limit="3"
            :file-list="fileList" :on-success="handleUploadSuccess" :on-error="handleUploadError"
            :on-remove="handleRemove" :before-upload="beforeUpload" accept="image/*" list-type="picture-card">
            <i class="el-icon-plus"></i>
          </el-upload>
          <div class="el-upload__tip">
            只能上传图片，最多3张
          </div>
        </el-form-item>
        <div class="mun-title">预约时间设置</div>
        <el-form-item label="预约日期" prop="bad_time">
          <el-date-picker v-model="addForm.bad_time" type="daterange" align="right" unlink-panels range-separator="-"
            format="yyyy - MM - dd " value-format="yyyy-MM-dd" start-placeholder="开始时间" end-placeholder="结束时间"
            @change="changeDatePicker">
          </el-date-picker>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="beforeClose">取 消</el-button>
        <el-button type="primary" :disabled="isDisabled" @click="addSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </el-main>
</template>
<script>
import {
  mapState
} from 'vuex'
import {
  waybillEdit,
  waybillDele,
  waybillPush,
  uploadNew,
  crateMuseum
} from '../../api.js'
export default {
  name: "factoryDriver",
  data() {
    return {
      fileList: [], // 用于存储上传的文件列表
      headers: {},
      imageArr: [],



      isAdd: true,
      isDisabled: false,
      addDialogVisible: false,
      addDisabled: false,
      is_check: false,
      breadcrumbName: '',
      breadcrumbPath: '',
      breadcrumbNameP: '',
      tableData: [{
        id: 1,
        sortID: 1,
        title: '文物文物',
        type: '馆藏文物',
        content: '文物文物内容内容',
        creatTime: '2025-02-29',
        coverImg: '',
        children: [{
          id: 2,
          sortID: 1,
          title: '文物子级',
          type: '馆藏文物',
          content: '文物子级文物子级文物子级文物子级文物子级',
          creatTime: '2025-02-29',
          coverImg: ''
        }],
      }],
      //查询栏默认展示数据
      formInlineD: {
        dataValue: [],
        value: ''
      },
      formInline: {
        ship_state: 0,
        transport_sn: '',
        start_dt: '',
        end_dt: '',
        page: 1,
        limit: 5
      },


      // bwg
      addForm: {
        sortID: '',
        title: '',
        type: '',
        createpersonid: "00001",
        createname: '管理员',
        content: '',
        coverImg: ''
      },

      editForm: {
        transport_sn: '',
        transport_total_amt: '',
        delivery_time: '',
        publish_phone: '',
        transport_weight: '',
        truck_type: '',
        delivery_need: [],
        nucleic_acid: '',
        green_code: -1,
        remark: '',
        delivery_need_extend: '',
        customer_json: [],
        domains: [{
          customer_name: '',
          customer_addr: '',
          customer_sn: '',
        }],
      },
      //分页
      total: 0,
      TimeType: [],
      needData: [],
      truckType: [{ name: '展厅展览', id: 0 }, { name: '馆藏文物', id: 1 }],
      dialogTitle: "",
      updateFrom: {
        transport_sn: '',
        transport_snArr: '',
      },
      addRules: {
        transport_sn: [{
          required: true,
          message: '请输入运单号',
          trigger: 'blur'
        }],
        truck_type: [{
          required: true,
          message: '请选择车辆类型',
          trigger: 'blur'
        }],
        publish_phone: [{
          required: true,
          message: '请输入发布人联系电话',
          trigger: 'blur'
        }],
        delivery_time: [{
          required: true,
          message: '请选择日期',
          trigger: 'blur'
        }],
        transport_total_amt: [{
          required: true,
          message: '请输入价格',
          trigger: 'blur'
        }],
        transport_weight: [{
          required: true,
          message: '请输入载重量',
          trigger: 'blur'
        }],
        delivery_need: [{
          required: true,
          message: '配送配置',
          trigger: 'change'
        }],
        nucleic_acid: [{
          required: true,
          message: '请选择核酸',
          trigger: 'blur'
        }],
        green_code: [{
          required: true,
          message: '请选择行程码',
          trigger: 'blur'
        }],
      },
    }
  },
  async mounted() {
    this.breadcrumbName = this.$route.query.breadcrumbName
    this.breadcrumbPath = this.$route.query.breadcrumbPath
    this.breadcrumbNameP = this.$route.query.breadcrumbNameP
    var date = new Date;
    var Simdate = this.DateTime(date.getTime() + 24 * 60 * 60 * 1000)
    // this.updateFrom.DeliveryDt = Simdate;
    this.formInlineD.value = Simdate
    // 暂时注册
    // this.getTableDate(this.formInline)
  },
  methods: {
    // 上传成功回调
    handleUploadSuccess(response, file) {
      this.imageArr.push(response.data)
      console.log('上传成功:', this.imageArr);
    },
    // 上传失败回调
    handleUploadError(err) {
      this.$message.error('文件上传失败，请稍后重试');
    },
    // 删除文件回调
    handleRemove(file, fileList) {
      this.imageArr = [];
      fileList.map(item => {
        this.imageArr.push(item.response.data)
      })
      console.log(this.imageArr)
    },
    // 上传前校验
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/'); // 校验是否为图片
      const isSizeValid = file.size / 1024 / 1024 < 5; // 校验图片大小，限制为 3MB

      if (!isImage) {
        this.$message.error('只能上传图片格式');
        return false;
      }
      if (!isSizeValid) {
        this.$message.error('图片大小不能超过 5MB');
        return false;
      }
      return true;
    },

    //编辑
    handleEdit(index, row) {
      this.isAdd = false
      this.dialogTitle = '编辑';
      // this.addForm.id = row.id;
      this.addForm.sortID = row.sortID;
      this.addForm.title = row.title
      this.addForm.type = row.type
      this.addForm.content = row.content;
      this.addForm.coverImg = row.coverImg
      this.addDialogVisible = true;
    },
    //表格分页
    handleCurrentChange(val) {
      this.formInline.page = val;
      this.getTableDate(this.formInline)
    },
    //表格查询
    onSearch() {
      this.formInline.page = 1;
      this.getTableDate(this.formInline)
    },
    handleShow(index, row) {
      this.isAdd = true
      this.dialogTitle = "添加"
      this.addDialogVisible = true;
    },
    //查看
    handleDetail(index, row) {
      this.$router.push({
        path: '/waybillMange/way_detail',
        query: {
          id: row.id,
          state: 0,
        }
      })
    },
    formatPassCheck(row, column, cellValue) {
      if (cellValue == 0) {
        return '不要'
      } else if (cellValue == 1) {
        return '要'
      }
    },
    //刪除
    handleDelete(index, row) {
      var _this = this
      _this.$confirm('此操作將刪除该数据, 是否继续？', '提 示', {
        confirmButtonText: '确 定',
        cancelButtonText: '取 消',
        center: true
      }).then(() => {
        var data = {
          transport_sn: row.transport_sn,
        }
        waybillDele(data).then(res => {
          if (res.ErrorCode == 0) {
            _this.getTableDate(_this.formInline);
            _this.$message.success("删除成功");
          } else {
            this.$message.error(res.ErrorMsg);
          }
        })
      }).catch(() => { });
    },

    //提交
    addSubmit() {
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          var _this = this;
          // _this.isDisabled = true;
          _this.addForm.coverImg = this.imageArr.join(",")
          var dataObj = JSON.parse(JSON.stringify(_this.addForm));
          if (_this.isAdd) {
            crateMuseum(dataObj).then(res => {
              if (res.ErrorCode == 0) {
                // _this.addDialogVisible = false
                // _this.$refs.editForm.resetFields();
                // _this.beforeClose();
                // _this.getTableDate(_this.formInline);
                // _this.isDisabled = false;
                _this.$message.success("添加成功");
              } else {
                _this.isDisabled = false;
                this.$message.error(res.ErrorMsg);
              }
            })
          } else {
            waybillEdit(dataObj).then(res => {
              if (res.ErrorCode == 0) {
                _this.$message.success("编辑成功");
                _this.$refs.editForm.resetFields();
                _this.beforeClose();
                _this.getTableDate(_this.formInline);
                _this.isDisabled = false;
                _this.addDialogVisible = false;
              } else {
                _this.isDisabled = false;
                this.$message.error(res.ErrorMsg);
              }
            })
          }
        }
      })
    },
    selectable(row, index) {
      return row.ship_state == 0
    },
    //发布
    handlePush(index, row) {
      this.updateFrom.transport_sn = row.transport_sn;
      this.typeSn = 1
      this.addSubmitPush();
    },
    onCheck() {
      this.typeSn = 2
      this.addSubmitPush();
    },
    //发布
    addSubmitPush() {
      var _this = this;
      _this.isDisabled = true;
      var data = {
        ship_state: 1
      }
      if (this.typeSn == 1) {
        data.transport_sn = _this.updateFrom.transport_sn
      } else {
        data.transport_sn = _this.updateFrom.transport_snArr
      }
      waybillPush(data).then(res => {
        if (res.ErrorCode == 0) {
          _this.addDialogVisible = false;
          _this.getTableDate(_this.formInline);
          _this.isDisabled = false;
          _this.$message.success("发布成功");
        } else {
          _this.isDisabled = false;
          this.$message.error(res.ErrorMsg);
        }
      })
    },
    removeDomain(item) {
      var index = this.editForm.domains.indexOf(item)
      if (index !== -1) {
        this.editForm.domains.splice(index, 1)
      }
    },
    addDomain() {
      this.editForm.domains.push({
        customer_name: '',
        customer_addr: '',
        customer_sn: '',
        // key: Date.now()
      });
    },
    beforeClose() {
      this.addDialogVisible = false
      this.editForm = {
        transport_sn: '',
        transport_total_amt: '',
        delivery_time: '',
        transport_weight: '',
        truck_type: '',
        delivery_need: [],
        nucleic_acid: '',
        delivery_need_extend: '',
        publish_phone: '',
        green_code: -1,
        remark: '',
        customer_json: [],
        domains: [{
          customer_name: '',
          customer_addr: '',
          customer_sn: '',
        }],
      }
    },
    formatNorm(row, column, cellValue) {
      return row.loadRangeMin + '~' + row.loadRangeMax
    },

    changeDatePicker(val) {
      if (val) {
        this.formInline.start_dt = val[0]
        this.formInline.end_dt = val[1]
      } else {
        this.formInline.start_dt = ''
        this.formInline.end_dt = ''
      }
    },

    DateTime(time) {
      var oDate = new Date(time),
        oYear = oDate.getFullYear(),
        oMonth = oDate.getMonth() + 1,
        oDay = oDate.getDate(),
        oTime = oYear + '-' + this.getzf(oMonth) + '-' + this.getzf(oDay);
      return oTime;
    },
    getzf(num) {
      if (parseInt(num) < 10) {
        num = '0' + num;
      }
      return num;
    },
    formatDept(row, column, cellValue) {
      return Array.prototype.join.call(cellValue, '，');
    },
    handleSelectionChange(selection) {
      console.log("selection", selection)
      if (selection.length == 0) {
        this.is_check = false
        this.updateFrom.transport_snArr = ""
      } else {
        this.updateFrom.transport_snArr = ""
        var UnifiedTimesNoArr = [];
        for (var i in selection) {
          UnifiedTimesNoArr.push(selection[i].transport_sn)
          this.updateFrom.transport_snArr = UnifiedTimesNoArr.join(',')
        }
        this.is_check = true
      }
    },
    //下载模板
    exportReport(e) {
      e.target.href = this.baseUrl + 'report/export/shipment_download_xlsx?code=shipment' +
        '&access_token=' + this.Token
    },

  },
  computed: {
    ...mapState({
      baseUrl: state => state.baseUrl,
      Token: state => state.access_token,
    }),
  },
}
</script>

<style scoped>
.title_import_title {
  padding: 0 20px;
  padding-bottom: 30px;
  font-weight: bold;
  font-size: 16px;
  color: #333;
}

.el-dialog__header {
  text-align: center;
}

.el-dialog__footer {
  text-align: center !important;
}

.img-table {
  width: 50px;
  height: 50px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.mun-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-left: 56px;
  padding-bottom: 20px;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>